package com.zengdada.authority.utils.where.result;

import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zsa
 * @date 2020/9/10 14:18
 */
public class MapperAnalysisResultMerge extends AnalysisResultMerge {

    private final Map<String, Object> paramValueMap = new HashMap<>(1);

    public Map<String, Object> getParamValueMap() {
        return paramValueMap;
    }

    @Override
    public boolean isNull() {
        return StringUtils.isAllBlank(getExtraFilter()) && paramValueMap.isEmpty();
    }

    public MapperAnalysisResultMerge() {
    }

    public MapperAnalysisResultMerge(AnalysisResult analysis) {
        super(analysis);
        for (int i = 0; i < getParamValues().size(); i++) {
            paramValueMap.put("param_" + i, getParamValues().get(i));
        }
        if (!isNull()) {
            replaceParam();
        }
    }

    private void replaceParam() {
        String extraFilter = getExtraFilter();
        String[] strings = extraFilter.split("\\{\\?}");
        int size = getParamValues().size();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < strings.length; i++) {
            builder.append(strings[i]);
            if (i < size) {
                builder.append(String.format("#{where.paramValueMap.param_%s}", i));
            }
        }
        setExtraFilter(builder.toString());
    }

}
